package com.limingru.newbee.service.impl;

import com.limingru.newbee.api.param.MallUserUpdateParam;
import com.limingru.newbee.api.vo.UserVO;
import com.limingru.newbee.common.Constants;
import com.limingru.newbee.common.ServiceResultEnum;
import com.limingru.newbee.dao.UserMapper;
import com.limingru.newbee.dao.UserTokenMapper;
import com.limingru.newbee.entity.User;
import com.limingru.newbee.entity.UserToken;
import com.limingru.newbee.service.UserService;
import com.limingru.newbee.util.MD5Util;
import com.limingru.newbee.util.NumberUtil;
import com.limingru.newbee.util.SystemUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserTokenMapper userTokenMapper;

    @Override
    public String login(String loginName, String passwordMD5) {

        User user = userMapper.selectByLoginNameAndPassword(loginName, MD5Util.MD5Encode(passwordMD5));

        if (user != null) {
            if (user.getLockedFlag() == 1) {
                return ServiceResultEnum.LOGIN_USER_LOCKED_ERROR.getText();
            }

            String newToken = getNewToken(System.currentTimeMillis() + "", user.getUserId());
            UserToken userToken = userTokenMapper.selectByUserId(user.getUserId());

            // 当前时间
            Date now = new Date();
            // 过期时间
            Date expireTime = new Date(now.getTime() + 2 * 24 * 3600 * 1000);
            if (userToken == null) {
                UserToken tokenObj = new UserToken();
                tokenObj.setUserId(user.getUserId());
                tokenObj.setToken(newToken);
                tokenObj.setUpdateTime(now);
                tokenObj.setExpireTime(expireTime);
                if (userTokenMapper.insertToken(tokenObj) > 0) {
                    return newToken;
                }
            } else {
                userToken.setToken(newToken);
                userToken.setUpdateTime(now);
                userToken.setExpireTime(expireTime);
                int result = userTokenMapper.updateToken(userToken);
                if (result > 0) {
                    return newToken;
                }
            }
        }

        return ServiceResultEnum.LOGIN_ERROR.getText();
    }

    /**
     * 获取新的 token
     * @param timeStr 时间字符串
     * @param userId 用户id
     * @return
     */
    private String getNewToken(String timeStr, Long userId) {
        String src = timeStr + userId + NumberUtil.generateRandomNum(4);
        return SystemUtil.generateToken(src);
    }

    @Override
    public boolean logout(Long userId) {
        return userTokenMapper.logout(userId) > 0;
    }

    @Override
    public String register(String loginName, String password) {
        if (userMapper.selectByLoginName(loginName) != null) {
            return ServiceResultEnum.SAME_LOGIN_NAME.getText();
        }

        User registerUser = new User();
        registerUser.setLoginName(loginName);
        registerUser.setNickName(loginName);
        registerUser.setIntroduceSign(Constants.USER_INTRO);
        registerUser.setPasswordMD5(MD5Util.MD5Encode(password));
        registerUser.setCreateTime(new Date());
        registerUser.setIsDeleted((byte) 0);
        registerUser.setLockedFlag((byte) 0);

        if (userMapper.register(registerUser) > 0) {
            return ServiceResultEnum.REGISTER_SUCCESS.getText();
        }
        return ServiceResultEnum.DB_ERROR.getText();
    }

    @Override
    public UserVO getUserInfo(String token) {
        UserVO userVO = userTokenMapper.selectUserByToken(token);
        return userVO;
    }

    @Override
    public String update(MallUserUpdateParam userUpdateParam) {
        if (!NumberUtil.isPhone(userUpdateParam.getLoginName())) {
            return ServiceResultEnum.LOGIN_NAME_IS_NOT_PHONE.getText();
        }
        User user = userMapper.selectUserByUserId(userUpdateParam.getUserId());
        if (user != null) {
            User userParam = new User();
            BeanUtils.copyProperties(userUpdateParam, userParam);
            if (userMapper.update(userParam) > 0) {
                return ServiceResultEnum.UPDATE_SUCCESS.getText();
            }
            return ServiceResultEnum.UPDATE_FAIL.getText();
        }
        return ServiceResultEnum.USER_NOT_EXIST.getText();

    }
}
